package sort;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

import sort.algorithm.Sorter;
import sort.record.RandomRecordsFactory;
import sort.record.Records;
import sort.record.RecordsFactory;
import sort.result.SortResult;
import sort.result.SortResultWatcher;
import sort.ui.components.ResultTableModel;
import sort.ui.components.SortControlWindow;
import sort.ui.components.TableWindow;

/**
 * @author masaru-gotou
 *
 */
public class SortSingleMain {
	private Sorter sorter;
	private Records records;
//	private ResultListWindow result_win;
	private ResultTableModel model;
	private TableWindow result_win;
	private SortControlWindow frame;

	private static final String argoNames[] = {
		"sort.algorithm.BubbleSort",
		"sort.algorithm.BucketSort",
		"sort.algorithm.InsertionSort",
		"sort.algorithm.QuickSort",
		"sort.algorithm.SelectionSort",
	};
	
	public SortSingleMain(String title) {
		frame = new SortControlWindow(title);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setAlgorithmNames(argoNames);
		
		frame.addInitActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent ev) {
				RecordsFactory factory = RandomRecordsFactory.getInstance();
				
				records = factory.create(frame.getRecordCount());
				frame.drawRecords(records);
				
				try {
					sorter = (Sorter)Class.forName(frame.getAlgorithmName()).newInstance();
					sorter.addObserver(frame);
				} catch (InstantiationException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
			}
			
		});
		frame.addStartActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				SortResultWatcher watcher = new SortResultWatcher(sorter.getName());
				watcher.start(records);
				Records sorted = sorter.sort(records.copy());
				watcher.finish(sorted);
				SortResult result = watcher.getResult();
				frame.setResult(result);
				model.add(result);
			}
			
		});
		
		model = new ResultTableModel();
		result_win = new TableWindow("result list",model);
		
		frame.pack();

		result_win.setLocation(frame.getLocation().x+frame.getWidth(),
							frame.getLocation().y);
		result_win.pack();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
//		PropertyConfigurator.configure("log4j.properties");
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				SortSingleMain main = new SortSingleMain("Sort Demo");
				main.result_win.setVisible(true);
				main.frame.setVisible(true);
			}
		});
	}
}
